/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.controller;

import com.cmti.skeleton.dto.SysDeptDto;
import com.cmti.skeleton.dto.SysLogDto;
import com.cmti.skeleton.dto.TreeNode;
import com.cmti.skeleton.dto.TreeNodeLayui;
import com.cmti.skeleton.entity.SysDept;
import com.cmti.skeleton.entity.SysLog;
import com.cmti.skeleton.service.DeptService;
import com.cmti.skeleton.util.Constants;
import com.cmti.skeleton.web.SysLogInterceptor;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

/**
 * 部门管理Controller
 *
 * @author Danny Lee
 */
@Controller
@RequestMapping("/dept")
public class DeptController {

    private final Log log = LogFactory.getLog(getClass());
    @Autowired
    private DeptService deptService;
//    @Autowired
//    private CommonDao commonDao;

    @RequestMapping("/list/ui")
    @RequiresPermissions("dept:list:ui")
    public String listUI() {
        return "sys/department";
    }

    /**
     * 列表显示部门数据
     *
     * @param dgm
     * @param sysDept
     * @param model
     */
//    @RequestMapping("/list/data")
//    public void listData(DataGridModel dgm, SysDeptDto sysDept, ModelMap model) {
//
//        List<SysDeptDto> sysDeptList = new ArrayList<SysDeptDto>();
//        long totalSysDept = 0;
//        sysDeptList = deptService.getDeptList(dgm, sysDept);
//        totalSysDept = deptService.totalDept(sysDept);
//
//        model.addAttribute("rows", sysDeptList);
//        model.addAttribute("totalSysDept", totalSysDept);
//
//    }
    /**
     * 增加预处理
     */
    @RequestMapping("/add/ui")
    @RequiresPermissions("dept:add:*")
    public void addUserUi() {
    }

    @RequestMapping(value = "/detail/ui")
    @RequiresPermissions("dept:detail:ui")
    public void detailUi() {
    }

    /**
     * 增加部门
     *
     * @param sysDept
     * @param model
     */
    @RequestMapping("/add/action")
    @RequiresPermissions("dept:add:*")
    public void addDept(SysDept sysDept, ModelMap model, HttpSession session, HttpServletRequest request) {
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("添加部门 ").append(sysDept.getName());
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());
        sysLog.setResult(SysLog.RESULT_FAIL);   // 默认失败

        long ifAdd = 0;
        boolean success = false;
        ifAdd = deptService.addDept(sysDept);
        if (ifAdd == 1) {
            sysLog.setResult(SysLog.RESULT_SUCCESS);
            success = true;
            //刷新deptJsonList
            refreshSessionDeptListJson(session);
        }
        model.addAttribute("success", success);

    }

    /**
     * 当增加，修改部门时更新session中的deptListJson
     */
    public void refreshSessionDeptListJson(HttpSession session) {

        //如果session中存在则更新session中的deptListJson
        if (session.getAttribute(Constants.DEPTLIST_JSON) != null) {

            List<TreeNode> deptJsonList = new ArrayList<TreeNode>();
            deptJsonList = deptService.getDeptTree();
            //更新部门列表json保存在session中
            session.setAttribute(Constants.DEPTLIST_JSON, deptJsonList);
        }
        if (session.getAttribute("deptTreeSelect") != null) {
            List<TreeNodeLayui> deptJsonList = new ArrayList<TreeNodeLayui>();
            deptJsonList = deptService.getDeptTreeList();
            //更新layui里部门下拉列表
            session.setAttribute("deptTreeSelect", deptJsonList);
        }
        if (session.getAttribute("deptList") != null) {
            SysDeptDto sysDeptDto = new SysDeptDto();
            List<SysDeptDto> departmentList = deptService.getDepartmentList(sysDeptDto);
            session.setAttribute("deptList", departmentList);//更新预览面板
        }
    }

    /**
     * 修改预处理
     *
     * @return
     *
     */
    @RequestMapping("/modify/ui")
    @RequiresPermissions("dept:modify:ui")
    public ModelAndView modifyUserUi() {
        MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
        return new ModelAndView(jsonView);
    }

    /**
     * 修改部门
     *
     * @param sysDept
     * @param model
     */
    @RequestMapping("/modify/action")
    @RequiresPermissions("dept:modify")
    public void modifyDept(SysDept sysDept, ModelMap model, HttpSession session, HttpServletRequest request) {
        // 先获取原来的信息，再做修改操作，否则影响到日志记录
        SysDept deptById = deptService.getDeptById(sysDept.getId());
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("修改部门 ").append(deptById.getName()).append(" 的信息");
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());
        sysLog.setResult(SysLog.RESULT_FAIL);   // 默认失败

        boolean ifUpdate = false;
        ifUpdate = deptService.updateDept(sysDept);
        if (ifUpdate == true) {
            sysLog.setResult(SysLog.RESULT_SUCCESS);
            //刷新deptJsonList
            refreshSessionDeptListJson(session);
        }
        model.addAttribute("success", ifUpdate);

    }

    @RequestMapping(value = "/delete/ui")
    @RequiresPermissions("dept:delete:*")
    public void deleteUi() {
    }

    /**
     * 删除部门
     *
     * @param deptId
     * @param model
     */
    @RequestMapping("/delete")
    @RequiresPermissions("dept:delete:*")
    public void deleteDept(@RequestParam("deptId") long deptId, ModelMap model, HttpSession session, HttpServletRequest request) {
        // 先获取原来的信息，再做修改操作，否则影响到日志记录
        SysDept deptById = deptService.getDeptById(deptId);
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("删除部门 ").append(deptById.getName());
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());
        sysLog.setResult(SysLog.RESULT_FAIL);   // 默认失败

        long ifDel = 0;
        boolean success = false;
        String errMsg = "";
        //根据deptId获取部门下的用户
        if (deptService.hasAssociatedUsers(deptId)) {
            errMsg += "该部门下还有用户 ";
        } //判断是否有子部门，
        else if (deptService.hasSubDepartments(deptId)) {
            errMsg += "该部门下还有子部门 ";
        } //如果部门下没有用户且没有子部门则可以删除部门
        else {
            ifDel = deptService.delDept(deptId);
        }
        if (ifDel > 0) {
            sysLog.setResult(SysLog.RESULT_SUCCESS);
            success = true;
            //刷新deptJsonList
            refreshSessionDeptListJson(session);
        }
        model.addAttribute("errMsg", errMsg);
        model.addAttribute("success", success);
    }

    /**
     * 跳转到树形显示部门列表
     *
     * @param model
     * @return
     */
    @RequestMapping("/list/ui/chart")
    @RequiresPermissions("dept:list:*")
    public String departmentChart(ModelMap model, HttpSession session) {
        //获取顶级部门
        SysDeptDto sysDeptDto = new SysDeptDto();
        List<SysDeptDto> departmentList;
        if (session.getAttribute("deptList") == null) {
            departmentList = deptService.getDepartmentList(sysDeptDto);
            session.setAttribute("deptList", departmentList);
        } else {
            departmentList = (List<SysDeptDto>) session.getAttribute("deptList");
        }
        model.addAttribute("deptList", departmentList);
        return "sys/deptChart";
    }

    /**
     * 显示部门树状结构
     *
     * @param writer
     * @param sysDeptDto
     * @param session
     * @throws IOException
     *
     */
    @RequestMapping("/list/deptTree")
    @RequiresPermissions("dept:list:*")
    public void genDeptTree(Writer writer, SysDeptDto sysDeptDto, HttpSession session) throws IOException {
        //获取顶级部门
        List<TreeNode> deptJsonList = new ArrayList<>();
        //定义部门列表字符串
        String deptListString;
        //如果session中存在
        if (session.getAttribute(Constants.DEPTLIST_JSON) != null) {

            deptListString = new ObjectMapper().writeValueAsString(session.getAttribute(Constants.DEPTLIST_JSON));
        } else {
            deptJsonList = deptService.getDeptTree();
            //将部门列表json保存在session中
            session.setAttribute(Constants.DEPTLIST_JSON, deptJsonList);
            deptListString = new ObjectMapper().writeValueAsString(deptJsonList);
        }

        writer.write(deptListString);
        writer.close();
    }

    @RequestMapping("/list/layui")
    @RequiresPermissions("dept:list:*")
    public void getDept(ModelMap model) {
        List<SysDeptDto> list = deptService.getListWithParentName();
        model.addAttribute("code", 0).addAttribute("msg", "").addAttribute("data", list).addAttribute("count", list.size());
    }

    @RequestMapping("/list/deptTreeLayui")
    @RequiresPermissions("dept:list:*")
    public void genDeptTreeLayui(Writer writer, HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("text/text;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        //获取顶级部门
        List<TreeNodeLayui> deptJsonList = new ArrayList<>();
        //定义部门列表字符串
        String deptListString;
        //如果session中存在
        if (session.getAttribute("deptTreeSelect") != null) {

            deptListString = new ObjectMapper().writeValueAsString(session.getAttribute("deptTreeSelect"));
        } else {
            deptJsonList = deptService.getDeptTreeList();
            //将部门列表json保存在session中
            session.setAttribute("deptTreeSelect", deptJsonList);
            deptListString = new ObjectMapper().writeValueAsString(deptJsonList);
        }

        writer.write(deptListString);
        writer.close();
    }
}
